<template>
  <el-page-header @click="goBack" :icon="this.ArrowLeft" content="编辑器" title="返回" style="margin: 15px 0"/>
  <v-md-editor v-model="text"
               @save="uploadNote"
               height="400px"
               :disabled-menus="[]"
               @upload-image="handleUploadImage"/>
  <el-dialog v-model="backDialogVisible" title="警告" width="30%" center>
    <span>
      返回后，会丢失所编辑的内容，是否确定返回？
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="backDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="this.$router.go(-1); backDialogVisible = false"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="saveDialogVisible" title="Warning" width="30%" center>
    <el-form
        label-position="top"
        label-width="100px">
      <el-form-item label="标题">
        <el-input
            v-model="title"
            placeholder="请输入标题"/>
      </el-form-item>
      <el-form-item label="简介">
        <el-input
            v-model="abs"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请输入简介"/>
      </el-form-item>
      <el-form-item label="封面图片">
        <el-input
            v-model="cover"
            placeholder="请输入图片url"/>
      </el-form-item>
      <el-form-item>
        <el-upload action="http://localhost:8085/api/uploadImage" list-type="picture-card"
                   :auto-upload="true"
                   :on-success="handleAvatarSuccess"
                   :show-file-list="false"
                   :with-credentials="true"
        >
          <template #default>
            <el-icon>
              <plus/>
            </el-icon>
          </template>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
              <span class="el-upload-list__item-actions">

          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><delete/></el-icon>
          </span>
        </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNode">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {ArrowLeft, Plus, ZoomIn, Download, Delete } from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {ref} from 'vue'

export default {
  name: "NoteEditor",
  data() {
    return {
      text: '',
      backDialogVisible: ref(false),
      saveDialogVisible: ref(false),
      title: ref(''),
      abs: ref(''),
      cover: ref(''),
      note: {},
      ArrowLeft,
      Plus,
      ZoomIn,
      Download,
      Delete,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      noteId: this.$route.query.id,
    }
  },
  mounted() {
    this.loadNote()
  },
  methods: {
    goBack() {
      if (this.text.length !== 0) {
        this.backDialogVisible = ref(true)
      } else {
        this.$router.go(-1)
      }
    },
    uploadNote(text, html) {
      if (text.length === 0) {
        ElMessage({
          message: '还未编辑内容不可以保存',
          type: 'warning',
        })
        return
      }
      this.note.contentMd = text
      this.note.contentHtml = html
      this.saveDialogVisible = ref(true)
    },
    saveNode() {
      this.$axios.post("note/save", {
        id: this.noteId,
        title: this.title,
        contentMd: this.note.contentMd,
        contentHtml: this.note.contentHtml,
        abs: this.abs,
        cover: this.cover
      }).then(success => {
        if (success.data.code === 200) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          this.$router.go(-1)
          this.saveDialogVisible = ref(false)
        } else {
          ElMessage({
            message: success.data.message,
            type: 'error',
          })
        }
      })
          .catch(fail => {
            console.log(fail);
          })
    },
    handleRemove(file) {
      console.log(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAvatarSuccess(res) {
      this.cover = ref(res)
    },
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      let formData = new FormData();
      formData.append("file", files[0])

      this.$axios.post("uploadImage", formData, {
        headers:{
          "Content-Type": "multipart/form-data"
        }
      }).then(success => {
        ElMessage({
          message: '上传图片成功',
          type: 'success',
        })
        insertImage({
          url: success.data,
          desc: '图片',

        });
      }).catch(fail => {
        console.log(fail)
      })

    },
    loadNote(){
      if (this.noteId) {
        let _this = this
        this.$axios.get("note/findById", {params: {id: this.noteId}})
            .then(success => {
              console.log(success)
              if (success.data.code === 200) {
                _this.text = success.data.data.contentMd
                _this.title = ref(success.data.data.title)
                _this.abs = ref(success.data.data.abs)
                _this.cover = ref(success.data.data.cover)
              } else {
                alert(success.data.message)
              }
            }).catch(fail => {
          console.log(fail);
        })
      }
    }
  }
}
</script>

<style scoped>

</style>